//
//  HAODE
//
//  Created by panquanReabam.com on 15/9/23.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "BusinessOrderExtAddViewController.h"
#import "ZJSwitch.h"
#import "MJRefresh.h"
#import "MemberCouponCell.h"
#import "MemberListViewController.h"
#import "CategoryListViewController.h"
#import "ToResiduePayViewController.h"
#import "MemberAddressViewController.h"

#import "OrderExtHeaderView.h"
#import "OrderExtHeaderModel.h"
#import "OrderExtFooterView.h"
@interface BusinessOrderExtAddViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource,MemberListViewControllerDelegate,OrderExtHeaderViewDelegate,MemberAddressViewControllerDelegate,OrderExtFooterViewDelegate,CategoryListViewControllerDelegate>
@property (strong, nonatomic) NSString*isEarnest;
@end
@implementation BusinessOrderExtAddViewController
{
    OrderExtFooterView*FooterView;
    NSMutableArray*DiscountRatecode ;
    NSMutableArray*DiscountRatecontent;
    NSMutableArray*EarnestRatecode;
    NSMutableArray*EarnestRatecontent;
    NSMutableArray*DeliveryTypecode;
    NSMutableArray*DeliveryTypecontent;
    double saveAccount;
    NSString*totalMoney;
    UILabel*youhuiquanjine;
    UIButton*totalPriceLabel;
    NSString*remakesAmountStr;
    NSMutableArray*title;
    NSMutableArray*couponId ;
    NSMutableArray*price ;
    NSMutableArray*couponIds ;
    NSMutableArray*prices ;
    NSMutableArray*totalPriceArray;
    NSString* userToken;
    UITableView*table;
}
@synthesize alt = alt;
@synthesize mDelegate;
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1]];
    lineLabel.alpha=1;
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
    self.title=@"确认订单";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
}

 //选择和修改会员
-(void)chooesBtn:(NSString *)str{
   
    MemberListViewController *detailViewController = [[MemberListViewController alloc] init];
    detailViewController.chooseState=@"选择";
    detailViewController.delegate = self;
    [self.navigationController pushViewController:detailViewController animated:YES];

}
 //更换地址
-(void)information:(NSString *)str{
   MemberAddressViewController *detailViewController = [[MemberAddressViewController alloc] init];
    detailViewController.chooseState=@"选择";
    detailViewController.delegate = self;
    detailViewController.userName=self.userName;
    detailViewController.phone =self.phone;
    detailViewController.sex=self.sex;
    detailViewController.memberId =self.memberId;
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    
}
- (void)MemberAddressViewController:(MemberAddressViewController *)MemberAddressViewController
                 memberIdStr:(NSString *)memberIdStr userName:(NSString *)userName phone:(NSString *)phone sex:(NSString *)sex consigneeName:(NSString *)consigneeName consigneeAddr:(NSString *)consigneeAddr consigneePhone:(NSString *)consigneePhone
{
   
    OrderExtHeaderView*HeaderView=[[OrderExtHeaderView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 300)];
    [HeaderView setSpecNameArray:self.specNameArray];
    [HeaderView setItemNameArray:self.itemNameArray];
    [HeaderView setItemCodeArray:self.itemCodeArray];
    [HeaderView setQuantityArray:self.quantityArray];
    [HeaderView setHeadImageFullArray:self.headImageFullArray];
    [HeaderView setItemIdArray:self.itemIdArray];
    [HeaderView setDealPriceArray:self.dealPriceArray];
    HeaderView.TotalMoney=self.TotalMoney;
    HeaderView. saveTypeStr=self.saveTypeStr;
    HeaderView.consigneeName=consigneeName;
    HeaderView.consigneePhone=consigneePhone;
    HeaderView.phone=phone;
    HeaderView.userName=userName;
    HeaderView.sex=sex;
    HeaderView.address=consigneeAddr;
    self.consigneeName=consigneeName;
    self.consigneeAddr=consigneeAddr;
    self.consigneePhone=consigneePhone;
    HeaderView.mDelegate=self;
    OrderExtHeaderModel *dataModel=[OrderExtHeaderModel dataModelWithDict:memberIdStr];
    HeaderView.model=dataModel;
    [self str:memberIdStr];
    HeaderView.frame=CGRectMake(0, 0, ScreenWidth, HeaderView.headerView.bottom);
    table.tableHeaderView=HeaderView;
}
- (void)secondViewController:(MemberListViewController *)secondViewController
                  memberIdStr:(NSString *)memberIdStr userName:(NSString *)userName phone:(NSString *)phone sex:(NSString *)sex consigneeName:(NSString *)consigneeName consigneeAddr:(NSString *)consigneeAddr consigneePhone:(NSString *)consigneePhone
{
    self.userName=userName;
    self.phone=phone;
    self.sex=sex;
    self.memberId=memberIdStr;
    self.consigneeName=consigneeName;
    self.consigneeAddr=consigneeAddr;
    self.consigneePhone=consigneePhone;
    OrderExtHeaderView*HeaderView=[[OrderExtHeaderView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 300)];
    [HeaderView setSpecNameArray:self.specNameArray];
    [HeaderView setItemNameArray:self.itemNameArray];
    [HeaderView setItemCodeArray:self.itemCodeArray];
    [HeaderView setQuantityArray:self.quantityArray];
    [HeaderView setHeadImageFullArray:self.headImageFullArray];
    [HeaderView setItemIdArray:self.itemIdArray];
    [HeaderView setDealPriceArray:self.dealPriceArray];
    HeaderView.TotalMoney=self.TotalMoney;
    HeaderView.saveTypeStr=self.saveTypeStr;
    HeaderView.consigneeName=consigneeName;
    HeaderView.consigneePhone=consigneePhone;
    HeaderView.phone=phone;
    HeaderView.userName=userName;
    HeaderView.sex=sex;
    HeaderView.address=consigneeAddr;
    HeaderView.mDelegate=self;
    OrderExtHeaderModel *dataModel=[OrderExtHeaderModel dataModelWithDict:memberIdStr];
    HeaderView.model=dataModel;
    [self str:memberIdStr];
    HeaderView.frame=CGRectMake(0, 0, ScreenWidth, HeaderView.headerView.bottom);
    table.tableHeaderView=HeaderView;
}
//有没有优惠券／／／／／／／／／／／
- (void)str:(NSString *)text
{
    price=[[NSMutableArray alloc]init];
    title=[[NSMutableArray alloc]init];
    couponId=[[NSMutableArray alloc]init];
    couponIds =[[NSMutableArray alloc]init];
    prices =[[NSMutableArray alloc]init];
    if (text!=nil ) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        if (Token ==nil) {
            Token=@"dd";
        }
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        
        [param setValue:text forKey:@"memberId"];
        [param setValue:totalMoney forKey:@"orderAmt"];
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        
        [HttpRequest requestData:@"Business/Coupon/getAvailableList" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    NSLog(@"---%@",severDataDict.dataDict);
                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                    for (NSDictionary* dicc in arrr )
                    {
                        [title addObject:[dicc valueForKey:@"title"]];
                        [couponId addObject:[dicc valueForKey:@"couponId"]];
                        [price addObject:[dicc valueForKey:@"price"]];
                }
                [table reloadData];
                }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                }}
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
            }];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.isEarnest=@"N";
    DeliveryTypecode=[[NSMutableArray alloc]init];
    DeliveryTypecontent=[[NSMutableArray alloc]init];
    EarnestRatecode=[[NSMutableArray alloc]init];
    EarnestRatecontent=[[NSMutableArray alloc]init];
    DiscountRatecode=[[NSMutableArray alloc]init];
    DiscountRatecontent=[[NSMutableArray alloc]init];
    totalPriceArray=[[NSMutableArray alloc]init];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    [table registerClass:[MemberCouponCell class] forCellReuseIdentifier:@"BusinessOrderExtAddViewController"];
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    OrderExtHeaderView*HeaderView=[[OrderExtHeaderView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 320)];
    [HeaderView setItemNameArray:self.itemNameArray];
     [HeaderView setItemCodeArray:self.itemCodeArray];
     [HeaderView setQuantityArray:self.quantityArray];
     [HeaderView setSpecNameArray:self.specNameArray];
     [HeaderView setHeadImageFullArray:self.headImageFullArray];
     [HeaderView setItemIdArray:self.itemIdArray];
     [HeaderView setDealPriceArray:self.dealPriceArray];
    HeaderView.TotalMoney=self.TotalMoney;
    HeaderView. saveTypeStr=self.saveTypeStr;
    HeaderView.mDelegate=self;
   
    OrderExtHeaderModel *dataModel=[OrderExtHeaderModel dataModelWithDict:@""];
    HeaderView.model=dataModel;
    
    [self str:self.memberId];
    HeaderView.frame=CGRectMake(0, 0, ScreenWidth, HeaderView.headerView.bottom);
    table.tableHeaderView=HeaderView;
    
    [self DiscountRate];
    [self EarnestRate];
    [self Distribution];
    FooterView=[[OrderExtFooterView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 400)];
    FooterView.mDelegate=self;
    [FooterView.switchs addTarget:self action:@selector(switchAction1:) forControlEvents:UIControlEventValueChanged];
    [FooterView.depositTextFied addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [FooterView.discountTextFied addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [FooterView.earnestRateSatBtn addTarget:self action:@selector(earnestRateSatBtn:) forControlEvents:UIControlEventTouchUpInside];
    [FooterView.discountRateSatBtn addTarget:self action:@selector(discountRateSatBtn:) forControlEvents:UIControlEventTouchUpInside];
    [FooterView.distributionSatBtn addTarget:self action:@selector(distributionSatBtn:) forControlEvents:UIControlEventTouchUpInside];
   table.tableFooterView=FooterView;
  
   
    for (int i = 0; i<self.dealPriceArray.count; i++) {
                double d;
                double d1;
                d =[self.dealPriceArray[i]doubleValue];
                d1 =[self.quantityArray[i]doubleValue];
                [totalPriceArray addObject:[NSString stringWithFormat:@"%f",d*d1]];
    }
            totalMoney = [totalPriceArray valueForKeyPath:@"@sum.floatValue"];
            remakesAmountStr= [totalPriceArray valueForKeyPath:@"@sum.floatValue"];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setPositiveFormat:@"###,##0.00;"];
            NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:totalMoney.doubleValue]];
            totalPriceLabel=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-48, ScreenWidth*430/750, 48)];
            totalPriceLabel.backgroundColor=[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
            totalPriceLabel.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
            [totalPriceLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            totalPriceLabel.alpha=0.8;
            [self priceStr:formattedNumberString];
            [self.view addSubview:totalPriceLabel];
            UIButton*buyBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth*430/750, ScreenHeight-48, ScreenWidth*320/750, 48)];
            [buyBtn setTitle:@"去收银" forState:UIControlStateNormal];
            buyBtn.backgroundColor=luseColor;
            [buyBtn addTarget:self action:@selector(buy:) forControlEvents:UIControlEventTouchUpInside];
            [buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.view addSubview:buyBtn];
    
            FooterView.discountAmountLabel.text=[NSString stringWithFormat:@"优惠后金额¥%@" ,formattedNumberString];
            NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"优惠后金额 ¥ %@" ,formattedNumberString]];
    
            [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:13.0]
     
                          range:NSMakeRange(0, 8)];
    
            [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:zhonghuiColor
     
                          range:NSMakeRange(0, 8)];
            FooterView.discountAmountLabel.attributedText = AttributedStr;

}



#pragma mark - Table view data source
#pragma mark - Table view delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [couponId count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MemberCouponCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BusinessOrderExtAddViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.saveAccount=YES;
    cell.title.text =[NSString stringWithFormat:@"%@ ¥ %@",[title objectAtIndex:indexPath.row],[price objectAtIndex:indexPath.row]];
    cell.title.font=[UIFont systemFontOfSize:15];
    cell.title.textColor=zhonghuiColor;
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@ ¥ %@",[title objectAtIndex:indexPath.row],[price objectAtIndex:indexPath.row]]];
    NSInteger count = [[title objectAtIndex:indexPath.row]length];
    NSString *string=[NSString stringWithFormat:@"%@",[price objectAtIndex:indexPath.row]];
    NSInteger count1 =[string length];
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:16.0]
     
                          range:NSMakeRange(count, count1+3)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:hongseColor
     
                          range:NSMakeRange(count, count1+3)];
    cell.title.attributedText = AttributedStr;
//    [cell.xuanzeBtn addTarget:self action:@selector(xiangqing:) forControlEvents:UIControlEventTouchUpInside];
//    cell.xuanzeBtn.tag=indexPath.row;
if  ([couponIds containsObject:[couponId objectAtIndex:indexPath.row]]){
        cell.xuanzeimage.image=[UIImage imageNamed:@"gous"];
        cell.saveAccount=NO;
        
    }
    if (couponId.count !=indexPath.row+1) {
        UIImageView *_xianview = [[UIImageView alloc]initWithFrame:CGRectMake(15,0, ScreenWidth-30, 0.5)];
        _xianview.image=[UIImage imageNamed:@"hengxian"];
        [cell.contentView addSubview:_xianview];
        
    }
    if (indexPath.row==0) {
        UILabel *lineLabel31=[[UILabel alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-30, 0.35)];
        lineLabel31.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel31];
        
    }
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  45;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    MemberCouponCell *sharecell=(MemberCouponCell *)cell;
    sharecell.saveAccount=! sharecell.saveAccount;
    
    if (!sharecell.saveAccount) {
        [couponIds addObject:[NSString stringWithFormat:@"%@",[couponId objectAtIndex:indexPath.row]]];
        [prices addObject:[NSString stringWithFormat:@"%@",[price objectAtIndex:indexPath.row]]];
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        MemberCouponCell *sharecell=(MemberCouponCell *)cell;
        sharecell.xuanzeimage.image=[UIImage imageNamed:@"gous"];
        double d1;
        NSNumber *sum = [prices valueForKeyPath:@"@sum.floatValue"];
        double d2;
        double d3;
        d1=sum.doubleValue;
        d2=totalMoney.doubleValue;
        d3=FooterView.discountTextFied.text.doubleValue;
        [self discountAmount:[NSString stringWithFormat:@"%.2f",d2-d1-d3]];
        [self heji];
 
    }
    else{
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        MemberCouponCell *sharecell=(MemberCouponCell *)cell;
        sharecell.xuanzeimage.image=[UIImage imageNamed:@"quans"];
        if (couponIds.count>0) {
            
            for (int i=0; i<couponIds.count; i++) {
                
                NSString *codeStr = [couponIds objectAtIndex:i];
                if ([codeStr isEqualToString:[NSString stringWithFormat:@"%@",[couponId objectAtIndex:indexPath.row]]] ) {
                    
                    [couponIds removeObjectAtIndex:i];//从指定索引移除
                    [prices removeObjectAtIndex:i];//从指定索引移除
                }
                double d1;
                NSNumber *sum = [prices valueForKeyPath:@"@sum.floatValue"];
                double d2;
                double d3;
                d1=sum.doubleValue;
                d2=totalMoney.doubleValue;
                d3=FooterView.discountTextFied.text.doubleValue;
                [self discountAmount:[NSString stringWithFormat:@"%.2f",d2-d1-d3]];
                [self heji];
}}}}

-(void)switchAction1:(UISwitch*)sender{
    
    if (sender.on ==YES) {
        self.isEarnest=@"Y";
        [self heji];
        [FooterView.depositTextFied setUserInteractionEnabled:YES];
    }
    if (sender.on == NO) {
        self.isEarnest=@"N";
        [self heji];
        [FooterView.depositTextFied setUserInteractionEnabled:NO];
    }
}
-(void)buy:(UIButton *)sender {
    
    if ([self.memberId length] <1)
    {
        [self showAlertMessage:@"请选择会员信息"];
    }
    else{
        
        if ([self.consigneeAddr length] <1)
        {
            [self showAlertMessage:@"地址不能为空！"];
        }
        else{
            
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString* Token = [user objectForKey:@"tokenId"];
            if (Token ==nil) {
                Token=@"dd";
            }
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:Token forKey:@"tokenId"];
            [params setValue:self.userName forKey:@"memberName"];
            [params setValue:self.memberId forKey:@"memberId"];
            [params setValue:self.DeliveryTypeCode forKey:@"deliveryType"];
            [params setValue:couponIds forKey:@"couponIds"];
            [params setValue:[prices valueForKeyPath:@"@sum.floatValue"] forKey:@"couponMoney"];//优惠券金额
            [params setValue:[NSString stringWithFormat:@"%.2f",  FooterView.discountTextFied.text.doubleValue]   forKey:@"discountMoney"];//discountMoney
            [params setValue:self.isEarnest  forKey:@"isEarnest"];
            [params setValue:[NSString stringWithFormat:@"%.2f",  FooterView.depositTextFied.text.doubleValue]   forKey:@"earnestMoney"];//earnestMoney
            [params setValue:self.consigneeAddr forKey:@"address"];
            [params setValue:self.consigneeName forKey:@"consignee"];
            [params setValue:self.consigneePhone forKey:@"phone"];
            [params setValue:FooterView.noteTextView.text  forKey:@"remark"];
            
            NSMutableArray *mDocumentLine=[NSMutableArray array];
            for (int i=0; i<self.itemCodeArray.count; i++) {
                
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                NSString *itemId = [self.itemIdArray objectAtIndex:i];
                NSString *quantity =[self.quantityArray objectAtIndex:i];
//              NSString *specId = [self.specIdArray objectAtIndex:i];
                NSString *specId =[NSString stringWithFormat:@"%@",[self.specIdArray objectAtIndex:i]];
                NSString *dealPrice = [self.dealPriceArray objectAtIndex:i];
                [dic setValue:quantity forKey:@"quantity"];
                [dic setValue:itemId forKey:@"itemId"];
                [dic setValue:dealPrice forKey:@"dealPrice"];
               if ([specId isEqualToString:@""]) {
                    
                }else{
                    
                    if ([specId isEqualToString:@"<null>"]) {
                        specId=@"";
                    }
                    [dic setValue:specId forKey:@"specId"];
                }
                
                [mDocumentLine addObject:dic];
                
                
            }
            
            
            [params setValue:mDocumentLine  forKey:@"items"];
            
            NSLog(@"33333333====%@",params);
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            [HttpRequest requestData:@"Business/Order/ExtAdd" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    
                    NSLog(@"33333333====%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
//                        [ClearFB clearUserData:userToken typeString:_saveTypeStr];

                        ToResiduePayViewController  *generateVC=[[ToResiduePayViewController alloc] init];
                        generateVC.sat=@"PlaceOrder";
                        generateVC.Dict=severDataDict.dataDict;
                        [self.navigationController pushViewController:generateVC animated:YES];
                        }else{
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }
    }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
            }}}

//1   一进来第一次为默认加载自定义类别   订单折扣百分比 discountRate／／／／／／订单定金百分比 earnestRate／／／／／／／／／／／／／／／／／／／／／／／／／
-(void)discountRateSatBtn:(UIButton *)sender {
    [self keyOn];
    CategoryListViewController*de = [[CategoryListViewController alloc] init];
    de.code=DiscountRatecode;
    de.content=DiscountRatecontent;
    de.sat=@"DiscountRate";
    de.mDelegate=self;
    [self.navigationController pushViewController:de animated:YES];
}

-(void)earnestRateSatBtn:(UIButton *)sender {
    [self keyOn];
    FooterView.switchs.on = YES;
    self.isEarnest=@"Y";
    [self heji];
    [FooterView.depositTextFied setUserInteractionEnabled:YES];
    CategoryListViewController*de = [[CategoryListViewController alloc] init];
    de.code=EarnestRatecode;
    de.content=EarnestRatecontent;
    de.sat=@"EarnestRate";
    de.mDelegate=self;
    [self.navigationController pushViewController:de animated:YES];
}

-(void)EarnestRate{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"EarnestRate" forKey:@"optionName"];
    [HttpRequest requestData:@"System/AppCodes" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                    [EarnestRatecode addObject:[dicc valueForKey:@"code"]];
                    [EarnestRatecontent addObject:[dicc valueForKey:@"content"]];
                }
                
                [FooterView.earnestRateSatBtn setTitle:EarnestRatecontent[0] forState:UIControlStateNormal];
                self.EarnestRateCode=EarnestRatecode[0];
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }}
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }}];
}

-(void)DiscountRate{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"DiscountRate" forKey:@"optionName"];
    
    [HttpRequest requestData:@"System/AppCodes" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                    [DiscountRatecode addObject:[dicc valueForKey:@"code"]];
                    [DiscountRatecontent addObject:[dicc valueForKey:@"content"]];
                }
                [FooterView.discountRateSatBtn setTitle:DiscountRatecontent[0] forState:UIControlStateNormal];
                   self.DiscountRateCode=DiscountRatecode[0];
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }}
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
}
-(void)distributionSatBtn:(UIButton *)sender {
    [self keyOn];
    CategoryListViewController*de = [[CategoryListViewController alloc] init];
    de.code=DeliveryTypecode;
    de.content=DeliveryTypecontent;
    de.sat=@"DeliveryType";
    de.mDelegate=self;
    [self.navigationController pushViewController:de animated:YES];
}
-(void)Distribution{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"DeliveryType" forKey:@"optionName"];
    
    [HttpRequest requestData:@"System/AppCodes" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                    [DeliveryTypecode addObject:[dicc valueForKey:@"code"]];
                    [DeliveryTypecontent addObject:[dicc valueForKey:@"content"]];
                    }
                self.DeliveryTypeCode=DeliveryTypecode[0];
               [FooterView.distributionSatBtn setTitle:DeliveryTypecontent[0] forState:UIControlStateNormal];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }}
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        }];
}
-(void)textViewEditing:(NSString *)textField{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    table .frame =CGRectMake(0, -280, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
   
}
//回收键盘
-(void)key:(NSString *)str{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    table .frame =CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
    [self keyOn];

}
-(void)keyOn{
    [FooterView.depositTextFied resignFirstResponder];
    [FooterView.noteTextView resignFirstResponder];
    [FooterView.discountTextFied resignFirstResponder];
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

-(void)discountAmount:(NSString *)formattedNumberString{
    [FooterView.discountAmountLabel removeFromSuperview];
    remakesAmountStr=formattedNumberString;
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString1 = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:formattedNumberString.doubleValue]];
    FooterView.discountAmountLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 135-90, ScreenWidth-40, 45)];
    FooterView.discountAmountLabel.text=[NSString stringWithFormat:@"优惠后金额¥%@" ,formattedNumberString1];
    FooterView.discountAmountLabel.textColor=[UIColor blackColor];
    FooterView.discountAmountLabel.textAlignment = NSTextAlignmentRight;
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"优惠后金额 ¥ %@" ,formattedNumberString1]];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:14.0]
     
                          range:NSMakeRange(0, 8)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:zhonghuiColor
     
                          range:NSMakeRange(0, 8)];
    FooterView.discountAmountLabel.attributedText = AttributedStr;
    [FooterView addSubview:FooterView.discountAmountLabel];
 
}
-(void)xuanze:(UIButton*)sender
{saveAccount=!saveAccount;
    if (saveAccount) {
        [sender setImage:[UIImage imageNamed:@"gous"] forState:UIControlStateNormal];
//      youhuiquanjine=[[UILabel alloc]initWithFrame:CGRectMake(xuanze.right+90, 45, 80, 45)];
        youhuiquanjine.text=@"¥ 0";
        youhuiquanjine.textColor=hongseColor;
        youhuiquanjine.font=[UIFont systemFontOfSize:16];
        [FooterView addSubview:youhuiquanjine];
    }
    else
    {[youhuiquanjine removeFromSuperview];
        [sender setImage:[UIImage imageNamed:@"quans"] forState:UIControlStateNormal];
     }
}
//算法／／／／／／／／／／／／／／／／／／／／／／／／／／／
-(void)DiscountRate:(NSString *)DiscountRate DiscountRateCode:(NSString *)DiscountRateCode{
    
    
    [FooterView.discountRateSatBtn setTitle:DiscountRate forState:UIControlStateNormal];
    double d1 = [totalMoney doubleValue];
    double d2 = [DiscountRateCode doubleValue];
    if (d2==0) {
        FooterView.discountTextFied.text=[NSString stringWithFormat:@"%.2f",d1*d2];
        double d1;
        NSNumber *sum = [prices valueForKeyPath:@"@sum.floatValue"];
        double d2;
        double d3;
        d1=sum.doubleValue;
        d2=totalMoney.doubleValue;
        d3=FooterView.discountTextFied.text.doubleValue;
        [self discountAmount:[NSString stringWithFormat:@"%.2f",d2-d1-d3]];
    }else {
        
        FooterView.discountTextFied.text=[NSString stringWithFormat:@"%.2f",d1*(1-d2)];
        double d1;
        NSNumber *sum = [prices valueForKeyPath:@"@sum.floatValue"];
        double d2;
        double d3;
        d1=sum.doubleValue;
        d2=totalMoney.doubleValue;
        d3=FooterView.discountTextFied.text.doubleValue;
        [self discountAmount:[NSString stringWithFormat:@"%.2f",d2-d1-d3]];
    }
    
    [self heji];
}
-(void)DeliveryType:(NSString *)DeliveryType DeliveryTypeCode:(NSString *)DeliveryTypeCode{
    
    self.DeliveryTypeCode=DeliveryTypeCode;
    [FooterView.distributionSatBtn setTitle:DeliveryType forState:UIControlStateNormal];
}
-(void)EarnestRate:(NSString *)EarnestRate EarnestRateCode:(NSString *)EarnestRateCode{
    
    [FooterView.earnestRateSatBtn setTitle:EarnestRate forState:UIControlStateNormal];
    double d1 = [remakesAmountStr doubleValue];
    double d2 = [EarnestRateCode doubleValue];
    NSLog(@"---%@",EarnestRateCode);
    self.EarnestRateCode=EarnestRateCode;
    if (d2==0) {
        FooterView.depositTextFied.text=[NSString stringWithFormat:@"%.2f",d1*d2];
        
    }else {
        
        FooterView.depositTextFied.text=[NSString stringWithFormat:@"%.2f",d1*d2];
    }
    
    [self heji];
}


-(void)textFieldEditing:(NSString *)textField{
    if (textField.intValue == 1)
    {
        [FooterView.discountRateSatBtn setTitle:@"自定义" forState:UIControlStateNormal];
        double d1 = [totalMoney doubleValue];
        double d2 = [FooterView.discountTextFied.text doubleValue];
        if (d2==0) {
            [self discountAmount:[NSString stringWithFormat:@"%.2f",d1-d2]];
        }else {
            [self discountAmount:[NSString stringWithFormat:@"%.2f",d1-d2]];
        }
        [self heji];
        if ( [FooterView.discountTextFied.text intValue]==0) {
            FooterView.discountTextFied.text=@"";
        }
        
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        table .frame =CGRectMake(0, -100, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    if (textField.intValue == 2)
    {
        if ([self.isEarnest isEqualToString:@"Y"]) {
            [FooterView.depositTextFied setUserInteractionEnabled:YES];
            [FooterView.earnestRateSatBtn setTitle:@"自定义" forState:UIControlStateNormal];
            
            [self heji];
            if ( [FooterView.depositTextFied.text intValue]==0) {
                FooterView.depositTextFied.text=@"";
            }
            
        }
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        table .frame =CGRectMake(0, -150, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
    }
    
    
}
- (void)textFieldDidChange:(UITextField *) TextField{
    
    if (TextField.tag == 1)
        
    {
        if (TextField.text.intValue<=totalMoney.intValue) {
            if (0<=TextField.text.intValue&&TextField.text.length<99)
            {
                [FooterView.discountRateSatBtn setTitle:@"自定义" forState:UIControlStateNormal];
                double d2 = [FooterView.discountTextFied.text doubleValue];
                if (d2==0) {
                    
                    double d1;
                    NSNumber *sum = [prices valueForKeyPath:@"@sum.floatValue"];
                    double d2;
                    double d3;
                    d1=sum.doubleValue;
                    d2=totalMoney.doubleValue;
                    d3=FooterView.discountTextFied.text.doubleValue;
                    [self discountAmount:[NSString stringWithFormat:@"%.2f",d2-d1-d3]];
                    [self heji];
                    
                }else {
                    double d1;
                    NSNumber *sum = [prices valueForKeyPath:@"@sum.floatValue"];
                    double d2;
                    double d3;
                    d1=sum.doubleValue;
                    d2=totalMoney.doubleValue;
                    d3=FooterView.discountTextFied.text.doubleValue;
                    [self discountAmount:[NSString stringWithFormat:@"%.2f",d2-d1-d3]];
                    [self heji];
                }}
            
        }else{
            
            [self showAlertMessage:@"整单折扣金额不能低于商品总价！"];
            TextField.text=@"";
        }
        
    }
    if (TextField.tag == 2)
        
    {if (0<=TextField.text.intValue&&TextField.text.length<99)
    {
        if (TextField.text.intValue<=remakesAmountStr.intValue) {
            self.EarnestRateCode=@"0";
            [FooterView.earnestRateSatBtn setTitle:@"自定义" forState:UIControlStateNormal];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setPositiveFormat:@"###,##0.00;"];
            NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:TextField.text.doubleValue]];
            [self priceStr:formattedNumberString];
        }else{
            
            [self showAlertMessage:@"定金金额不能低于优惠后的总价！"];
            TextField.text=@"";
        }}}
    
}
-(void)heji{
    if ([self.isEarnest isEqualToString:@"Y"]) {
        double d1 = [remakesAmountStr doubleValue];
        if ([FooterView.earnestRateSatBtn.titleLabel.text isEqualToString:@"自定义"] ) {
       
        }else{
            double d2 = [self.EarnestRateCode doubleValue];
            FooterView.depositTextFied.text=[NSString stringWithFormat:@"%.2f",d1*d2];
        }
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setPositiveFormat:@"###,##0.00;"];
        NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:FooterView.depositTextFied.text.doubleValue]];
        [self priceStr:formattedNumberString];
    }
    if ([self.isEarnest isEqualToString:@"N"]) {
        NSString *subString2 = [FooterView.discountAmountLabel.text substringFromIndex:8];       //@"2345"
        [self priceStr:subString2];
    }
    
}

-(void)priceStr:(NSString *)str {
    [totalPriceLabel setTitle:[NSString stringWithFormat:@"  金额 ￥%@",str] forState:UIControlStateNormal];
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"  金额 ￥%@",str]];
    
    [AttributedStr1 addAttribute:NSFontAttributeName
     
                           value:[UIFont systemFontOfSize:14.0]
     
                           range:NSMakeRange(0, 6)];
    
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:[UIColor whiteColor]
     
                           range:NSMakeRange(0, 6)];
    
    
    totalPriceLabel.titleLabel.attributedText = AttributedStr1;
    
}
@end
